<template lang="pug">
el-upload.bwt-file-upload(
  :action="actionUrl",
  :headers="headers",
  :file-list="fileList",
  :on-success="handleSuccess",
  :on-error="handleError",
  :on-remove="handleRemove",
  :before-upload="beforeUpload",
  :on-exceed="onExceed",
  :limit="limit"
)
  el-button(type="primary" :loading="isUploading") {{ buttonName }}
  template(#tip)
    .el-upload__tip 换乘站只需上传一次
</template>

<script setup name="BwtFileUpload">
import { getToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  buttonName: {
    type: String,
    default: '点击上传'
  },
  fileType: {
    type: Array,
    default: () => ['.zip']
  },
  limit: {
    type: Number,
    default: 1
  }
});
const actionUrl = import.meta.env.VITE_APP_OPEN_API + '/openapi/file/v1/upload';
const headers = {
  appId: '1102250547165007872'
};
const emit = defineEmits();
const { proxy } = getCurrentInstance();
const fileList = ref([]);
const isUploading = ref(false);
watch(() => props.modelValue, (newValue, oldValue) => {
  if (newValue) {
    const urlArr = newValue.split('/')
    fileList.value = [
      {
        name: urlArr[urlArr.length - 1],
        url: newValue
      }
    ]
  } else {
    fileList.value = []
  }
})
function onExceed(files, fileList) {
  ElMessage.warning('重新上传，请先删除原来的场景资源包')
}
function handleSuccess(res, file) {
  isUploading.value = false
  if (res.success) {
    const fileUrl = (res.result || {}).file_path
    const fileInfo = res.result || {}
    emit('update:modelValue', fileUrl)
    emit('uploadSuccess', fileInfo)
  } else {
    fileList.value = []
    ElMessage.error(res.errmsg)
  }
}
function handleError() {
  ElMessage.error('上传失败')
  isUploading.value = false
}
function handleRemove() {
  emit('clearUpload')
}
function beforeUpload(file) {
  isUploading.value = true
  const fileName = file.name
  const fileType = fileName.substring(fileName.lastIndexOf('.'))
  if (!props.fileType.includes(fileType)) {
    ElMessage.error(`只支持${props.fileType.toString()}类型文件`)
    isUploading.value = false
    return false
  }
  const limitSize = file.size / 1024 / 1024 < 1024
  if (!limitSize) {
    ElMessage.error('上传文件大小不能超过 1GB!')
    isUploading.value = false
    return false
  }
}
</script>
